class GeneralNewsLettersController < ApplicationController
  load_and_authorize_resource
  before_filter :load_data

  #control general de acceso cancan, segun los permisos definidos en ability.rb
  authorize_resource :resource => :contact_profiles

  def load_data
    @country_count_columns_by_row = Setting.view_contact_general_news_letter_countries_by_row
    @countries = Country.find(:all, :conditions => "use_for_sale = true", :order => "name")
    session[:entity_caller] = "GENERAL_NEWS_LETTER"
  end

  def redirect_back
      redirect_back_or_default params[:url]
  end

  # GET /general_news_letters
  # GET /general_news_letters.xml
  def index
    save_redirect_back request.request_uri
    @states = ["state_all", GeneralNewsLetter::STATE_ALREADY_SENT, GeneralNewsLetter::STATE_READY_TO_SEND]
    search_description = params[:search_description] || ""
    search_state = params[:search_state]
    @general_news_letters = GeneralNewsLetter.search(search_description, search_state, params[:page])

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @general_news_letters }
    end
  end

  # GET /general_news_letters/1
  # GET /general_news_letters/1.xml
  def show
    @general_news_letter = GeneralNewsLetter.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @general_news_letter }
    end
  end

  # GET /general_news_letters/new
  # GET /general_news_letters/new.xml
  def new
    @general_news_letter = GeneralNewsLetter.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @general_news_letter }
    end
  end

  # GET /general_news_letters/1/edit
  def edit
    @general_news_letter = GeneralNewsLetter.find(params[:id])
  end

  # POST /general_news_letters
  # POST /general_news_letters.xml
  def create
    @general_news_letter = GeneralNewsLetter.new(params[:general_news_letter])
    @general_news_letter.state = GeneralNewsLetter::STATE_READY_TO_SEND
    countries = params['countries'] || []
    countries.each do |country_id|
      @general_news_letter.countries << Country.find(country_id.to_i)
    end
            
    respond_to do |format|
      if @general_news_letter.save
        flash[:notice] = t('msg_record_successfully_created')
        format.html { redirect_to(@general_news_letter) }
        format.xml  { render :xml => @general_news_letter, :status => :created, :location => @general_news_letter }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @general_news_letter.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /general_news_letters/1
  # PUT /general_news_letters/1.xml
  def update
    @general_news_letter = GeneralNewsLetter.find(params[:id])
    countries = params['countries'] || []
    #borro de la instancia los paises que ya no esten en el array
    @general_news_letter.countries.each do |country|
      if !countries.include?(country.id.to_s)
        @general_news_letter.countries.delete(country)
      end
    end
    #agrego los paies que estan en el array pero no en la instancia
    countries.each do |country_id|
      country = Country.find(country_id)
      if !@general_news_letter.countries.include?(country)
        @general_news_letter.countries << country
      end
    end

    respond_to do |format|
      if @general_news_letter.update_attributes(params[:general_news_letter])
        flash[:notice] = t('msg_record_successfully_updated')
        format.html { redirect_to(@general_news_letter) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @general_news_letter.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /general_news_letters/1
  # DELETE /general_news_letters/1.xml
  def destroy
    @general_news_letter = GeneralNewsLetter.find(params[:id])

    if @general_news_letter.state == GeneralNewsLetter::STATE_READY_TO_SEND
      @general_news_letter.destroy
      respond_to do |format|
        format.html { redirect_to(general_news_letters_url) }
        format.xml  { head :ok }
      end

    else
      #significa que esta ya estan enviadas. No se pueden borrar por la applicacion
      flash[:error] = t('lbl_general_news_letter_invalid_delete_already_sent')
      redirect_to(general_news_letters_url)
    end
  end

  def general_news_letter_materials_index    

    save_redirect_back request.request_uri

    #se cargan los materiales para el popup
    @materials  = Material.search_engine nil

    @general_news_letter = GeneralNewsLetter.find(params[:id])
    search_title = params[:search_title] || ""
    @general_news_letters_materials = GeneralNewsLettersMaterial.search(@general_news_letter.id, search_title, params[:page])
  end

  def general_news_letter_add_material
    #busco cual es el ultimo material definido para esta lista
    last_general_news_letter_material = GeneralNewsLettersMaterial.find(:first, :order => "order_list desc", :conditions => ["general_news_letter_id = ?",  params[:general_news_letter_id]])

    #obtengo las instancias de material y wish_list involucradas
    general_news_letter = GeneralNewsLetter.find(params[:general_news_letter_id])
    material = Material.find(params[:material_id])

    #agrego el material a la lista
    general_news_letter_material = GeneralNewsLettersMaterial.new
    general_news_letter_material.material = material
    general_news_letter_material.general_news_letter = general_news_letter
    if last_general_news_letter_material.nil?
      general_news_letter_material.order_list = 1
    else
      general_news_letter_material.order_list = last_general_news_letter_material.order_list + 1
    end

      if general_news_letter_material.save
        flash[:notice] = t('lbl_material_add_general_news_letter_ok')
      else
        flash[:error] = t('lbl_material_add_general_news_letter_error')
      end
      redirect_back_or_default general_news_letter_materials_path(params[:general_news_letter_id])
  end

  def general_news_letter_delete_material
    #se busca el registro asociado a esta lista-material
    general_news_letter_material = GeneralNewsLettersMaterial.find(params[:materials_general_news_letter_id])
    general_news_letter_material.destroy
    redirect_back_or_default general_news_letter_materials_path
  end

  def general_news_letter_up_material
    #se busca el registro asociado a esta lista-material
    general_news_letter_material = GeneralNewsLettersMaterial.find(params[:materials_general_news_letter_id])

    #busco el primer material con order < al registro elegido
    general_news_letter_material_prev = GeneralNewsLettersMaterial.find(:first,:order => "order_list DESC", :conditions => ["general_news_letter_id = ? and order_list < ?", general_news_letter_material.general_news_letter_id, general_news_letter_material.order_list])

    if !general_news_letter_material_prev.nil?
      #swap
      temp = general_news_letter_material.order_list
      general_news_letter_material.order_list = general_news_letter_material_prev.order_list
      general_news_letter_material_prev.order_list = temp
      #save
      general_news_letter_material.save
      general_news_letter_material_prev.save
    end

    redirect_back_or_default general_news_letter_materials_path
  end

  def general_news_letter_down_material
    #se busca el registro asociado a esta lista-material
    general_news_letter_material = GeneralNewsLettersMaterial.find(params[:materials_general_news_letter_id])

    #busco el primer material con order > al registro elegido
    general_news_letter_material_next = GeneralNewsLettersMaterial.find(:first,:order => "order_list", :conditions => ["general_news_letter_id = ? and order_list > ?", general_news_letter_material.general_news_letter_id, general_news_letter_material.order_list])

    if !general_news_letter_material_next.nil?
      #swap
      temp = general_news_letter_material.order_list
      general_news_letter_material.order_list = general_news_letter_material_next.order_list
      general_news_letter_material_next.order_list = temp
      #save
      general_news_letter_material.save
      general_news_letter_material_next.save
    end

    redirect_back_or_default general_news_letter_materials_path
  end
end
